﻿using System;
using System.Collections.Generic;

namespace Having.Site.Data.Lambda
{


    /// <summary>
    /// 解析表达式（MYSQL数据库）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class MYSQLDataQuery<T> : BaseSQLDataQuery<T>, IDataQuery<T> where T : class, new()
    {
        string limit = "";

        /// <summary>
        /// 是否允许有参数值
        /// </summary>
        /// <param name="_ispara"></param>
        public MYSQLDataQuery(bool _ispara=true):base()
        {
            
        }

        /// <summary>
        /// 随机排序（性能不好，请谨慎使用）
        /// </summary>
        /// <returns></returns>
        public new IDataQuery<T> OrderByRandom()
        {
            Olist.Add(" RAND()");
            return this;
        }

        public new DataQueryResult Res
        {
            get
            {
                return new DataQueryResult(lr.Parameters, ToSql(), Dic);
            }
        }
        /// <summary>
        /// 返回生成的Sql
        /// </summary>
        /// <returns></returns>
        public new string ToSql()
        {
            string sql = "";
            string Tb = "["+typeof(T).Name+"]";
            string w = "";
            var i = 0;
            //查找方式
            if (mlist.ContainsKey("Delete"))
            {
                i = 1;
            }
            if (mlist.ContainsKey("Insert"))
            {
                i = 2;
            }
            if (mlist.ContainsKey("Select"))
            {
                i = 3;
            }
            if (mlist.ContainsKey("Update"))
            {
                i = 4;
            }
            if (mlist.ContainsKey("PageList"))
            {
                i = 5;
            }



            switch (i)
            {
                case 0://没有方法的时候，使用select
                case 5://PageList
                case 3://select
                    sql = "select ";
                    var plc = 0;
                    if (plist.ContainsKey("Take"))
                    {
                        //sql += " top " + plist["Take"];
                        limit = " limit 0," + plist["Take"];
                        plc = 1;
                    }
                    if (plist.ContainsKey("Distinct"))
                    {
                        sql += " Distinct " + plist["Distinct"];
                        plc++;
                    }

                    if (plist.Count-plc > 0)
                    {
                        foreach (var item in plist)
                        {
                            if (item.Key != "Filter")
                            {
                                if (item.Key != "Take")
                                {
                                    sql += " " + item.Key + "(" + item.Value + "),";
                                }
                            }
                            else
                            {
                                sql +=" "+ item.Value.Replace(" and ",",").Replace(" or ",",") + ",";
                            }
                        }
                    }
                    else
                    {
                        sql += " * ,";
                    }
                    if (mlist.ContainsKey("Select") && !string.IsNullOrWhiteSpace(mlist["Select"]))
                    {
                        w += mlist["Select"];
                    }

                    sql = sql.Substring(0, sql.Length - 1);
                    sql += " from " + Tb ;
                    //if (Locklist.Count > 0)
                    //{
                    //    sql += " with(" + Locklist["with"] + ") ";
                    //}
                    if (Joinlist.Count > 0)
                    {
                        foreach (var item in Joinlist)
                        {
                            sql +=" "+item.Key+" "+item.Value;
                        }
                        
                    }
                    break;
                case 1://delete
                    sql += "delete from " + Tb;
                    //if (Locklist.Count > 0)
                    //{
                    //    sql += " with(" + Locklist["with"] + ") ";
                    //}
                    if (mlist.ContainsKey("Delete") && !string.IsNullOrWhiteSpace(mlist["Delete"]))
                    {
                        w = mlist["Delete"];
                    }
                    break;
                case 2://Insert
                    sql += " insert into " + Tb;
                    //if (Locklist.Count > 0)
                    //{
                    //    sql += " with(" + Locklist["with"] + ") ";
                    //}
                    if (mlist.ContainsKey("Insert") && !string.IsNullOrWhiteSpace(mlist["Insert"]))
                    {
                        var candv = mlist["Insert"].Split(new string[] { " and " }, StringSplitOptions.RemoveEmptyEntries);
                        var coms = new List<string>();
                        var vals = new List<string>();
                        foreach (var item in candv)
                        {
                            string[] its = item.Replace("(", "").Replace(")", "").Split('=');
                            coms.Add(its[0].Trim());
                            vals.Add(its[1].Trim());
                        }
                        sql += " (" + string.Join(",", coms) + ") values (" + string.Join(",", vals) + ")";
                    }
                    break;
                case 4://Update
                    sql += "update " + Tb;
                    //if (Locklist.Count > 0)
                    //{
                    //    sql += " with(" + Locklist["with"] + ") ";
                    //}
                    if (!string.IsNullOrWhiteSpace(mlist["Update"]))
                    {
                        sql += " set " + mlist["Update"].Replace("(", " ").Replace(")", " ").Replace(" and ", " , ").Replace(" or ", " , ");
                    }
                    break;
            }
            

            //判断是否有where条件的语句
            if (wlist.Count > 0)
            {
                foreach (var item in wlist)
                {
                    if (item.Value.IndexOf("GetShotDate") >= 0)
                    {
                        var vas = item.Value.Trim().Split(new string[] { " ", "GetShotDate", ")", "(" }, StringSplitOptions.RemoveEmptyEntries);
                        w += (w.Length > 0 ? " and " : "") + "(DATE_FORMAT(" + vas[0] + ",'%Y%m%d')" + vas[1] + ")";
                        continue;
                    }
                    w += (w.Length > 0 ? " and " : "") + item.Value;
                }
            }
            if (w.Length > 0) {
                sql += " where " + w;
            }
            //判断是否有Groupby条件的语句
            if (Glist.Count > 0)
            {
                sql += " Group By " + Glist["GroupBy"];
            }
            if (Olist.Count > 0)
            {
                if (i != 5)
                {
                    sql += " Order By " + string.Join(",", Olist);
                }
                else
                {
                    Dic["OrderBy"] = string.Join(",", Olist).Replace("[","").Replace("]","");
                }
            }
            //判断是否有having的语句
            if (Havinglist.Count > 0)
            {
                List<string> li = new List<string>();
                foreach (var item in Havinglist)
                {
                    li.Add(item.Value);
                }
                sql += " Having " + string.Join(" and ", li);
            }
            if (!string.IsNullOrWhiteSpace(limit))
            {
                sql += limit;
            }
            return sql.Replace("[","").Replace("]","");


        }
        
    }
}
